package module.building.controller
{
	import code.ui.BaseRingCircle;
	
	import com.darwin.darwinIsometric.core.IsoObject;
	import com.darwin.darwinMVC.mvc.Command;
	import com.darwin.darwinNameSpace.darwin;
	import com.darwin.darwinUI.manager.ToolTipManager;
	import com.darwin.darwinUI.manager.UIManager;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import main.App;
	import main.AppControllerList;
	import main.AppNet;
	import main.mvc.GController;
	
	import module.building.cmds.BuildCommand;
	import module.building.consts.BuildConst;
	import module.building.event.BuildEvent;
	import module.building.model.BuildingModelData;
	import module.building.model.dataObj.BuildingObj;
	import module.building.model.dataObj.EquipObj;
	import module.building.view.Recruit.FarmProducePanel;
	import module.building.view.Recruit.RecruiteArmsPanel;
	import module.building.view.buildingButtonsPanel.BuildingButtonsPanel;
	import module.building.view.buildingConfirmPanel.BuildingConfirmPanel;
	import module.building.view.buildingListPanel.BuildListItem;
	import module.building.view.buildingListPanel.BuildingListPanel;
	import module.building.view.buildingTips.BuildingResourceTips;
	import module.building.view.buildingTips.BuildingTips;
	import module.building.view.buildingUpPanel.BuildingUpTabView;
	import module.building.view.produceweapon.WeaponProducePanel;
	import module.edittroop.cmds.EditTroopCmdConst;
	import module.edittroop.model.dataObj.ArmsConfigObj;
	import module.main.cmds.MainCmdConst;
	import module.main.model.dataObj.UserInfoObj;
	import module.scene.cmds.SceneCommand;
	import module.scene.consts.ActionType;
	import module.scene.consts.SceneConst;
	import module.scene.model.dataObj.IsoDataObj;
	import module.scene.view.iso.BuildingIsoObject;
	import module.scene.view.iso.base.JusticeIsoObject;
	
	import org.osmf.events.BufferEvent;
	
	/**
	 * 建筑控制器 
	 * @author hc
	 */
	public class BuildingController extends GController
	{
		
		public function BuildingController()
		{
			super();
		}
		
		override public function start():void
		{
			super.start();
			init();
		}
		
		/**
		 * 建造前的初始信息 
		 */
		private var _originUserInfo:UserInfoObj;
		
		/**
		 * 记录一次DIY过程中玩家整个操作流程 
		 */
		private var _diyHistoryArray:Array;
		
		private var _selectedBuilding:BuildingIsoObject;
		/**
		 * 建筑数据 
		 */
		private var _buildingModelData:BuildingModelData;
		/**
		 * 包含建筑信息的数组 
		 */
		private var buildingInfoArray:Array;		
		/**
		 * 建筑列表面板 
		 */
		private var _buildingListPanel:BuildingListPanel;
		private var _recruiteArmsPanel:RecruiteArmsPanel;
		/**
		 * 建筑按钮面板 
		 */
		private var _buildingButtonsPanel:BuildingButtonsPanel;
		/**
		 * 建筑确认面板 
		 */
		private var _buildingConfirmPanel:BuildingConfirmPanel;
		/**
		 * 建筑资源不足提示框 
		 */
		private var resourceTips:BuildingResourceTips
		private var _buildingRing:BaseRingCircle;  //环形菜单
		private var _isShowRing:Boolean; //标注 是否已弹出环形菜单 。避免被建筑TIP替换
		/**
		 *弓箭兵装备生产面板
		 */		
		private var _archerEquipPanel:WeaponProducePanel;
		/**
		 * 步兵装备生产面板
		 */		
		private var _infantryEquipPanel:WeaponProducePanel;
		/**
		 *骑兵装备生产面板 
		 */		
		private var _cavalryEquipPanel:WeaponProducePanel;
		
		private var _farm:FarmProducePanel;
		
		private var _clickIso:JusticeIsoObject;
		
		private var _buildingUpTabView:BuildingUpTabView;
		
		private var _armsConfigArray:Array;
		
		private var _addIsoDic:Dictionary;
		
		/**
		 * 删除建筑列表
		 */
		private var _removeIsoDic:Dictionary;
		
		/**
		 * 移动建筑列表
		 */
		private var _moveIsoDic:Dictionary;
		
		private function init():void
		{
			_buildingModelData = new BuildingModelData;
			_armsConfigArray = _buildingModelData.armsConfigArr;
			buildingInfoArray = _buildingModelData.buildingConfigArr;
			addRegister();
			initListener();
			
			//			//	测试用
			//			var timer:Timer = new Timer(10000, 1);
			//			
			//			timer.addEventListener(TimerEvent.TIMER_COMPLETE, handler);
			//			timer.start();
		}
		
		//		private function handler(e:TimerEvent):void
		//		{
		//			trace("+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+");
		//			var value:Object = {};
		//			value.eId = "1322814877009";
		//			value.type = "gold";
		//			value.num = 100;
		//			var harvestCmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_DROP_ITEM);
		//			harvestCmd.data = value;
		//			dispatch(harvestCmd);
		////			_buildingModelData.sendBuildProduction(value);
		//			
		//		}
		
		private function addRegister():void
		{
			register(BuildCommand.CLICK_BUILD_OPEN_BUTTON, buildCmdHandler);
			register(BuildCommand.CONSTRUCTION_COMPLETE, buildCmdHandler);
			register(BuildCommand.SHOW_BUILDING_UPGRADE, showBuildingUp);
			register(SceneCommand.SCENE_CMD_CLICK_ISO, isoClickHandler);
			register(SceneCommand.SCENE_CMD_STARTDRAG,hideBuildingRing);
			register(SceneCommand.SCENE_CMD_MOUSE_DOWN,sceneDownHandler);
			register(SceneCommand.SCENE_CMD_MOUSE_MOVE, sceneCmdHandler);
			register(SceneCommand.SCENE_CMD_ISO_DISPATCH_EVENT,sceneCmdHandler);
			register(SceneCommand.SCENE_ACTION_ADD, sceneCmdHandler);
			register(SceneCommand.SCENE_ACTION_MOVE, sceneCmdHandler);
			register(SceneCommand.SCENE_ACTION_REMOVE, sceneCmdHandler);
			register(BuildCommand.BUILD_CONSTRUCTION_SUCCESS,buildConstructionHandler);
			register(BuildCommand.BUILD_PRODUCE, buildProduce);
			register(BuildCommand.BUILD_HARVEST, buildHarvest);
			register(BuildCommand.REMOVE_CONSTRUCTION_SUCCESS,buildConstructionHandler);
			register(BuildCommand.MOVE_CONSTRUCTION_SUCCESS,buildConstructionHandler);
			register(BuildCommand.BUILD_UPGRADE_START, upgradeCmdHandler);
			register(BuildCommand.BUILD_UPGRADE_END, upgradeCmdHandler);
		}
		
		private function initListener():void{
			appCommonView.appContainer.uiLayer.addEventListener(MouseEvent.CLICK,uiLayerClick);
		}
		
		/**
		 *	农场生产 
		 * 	@param e
		 */		
		private function farmProduceHandler(e:BuildEvent):void
		{
			UIManager.getPopUpManager().removePopUp(_farm);
			var farmProduceMes:Object = {};
			farmProduceMes.serverId = e.data.serverId;
			farmProduceMes.eid = e.data.eId;
//			_buildingModelData.sendBuildProduction(farmProduceMes);
		}
		
		/**
		 *	兵营招募 
		 */		
		private function armProduceHandler(e:BuildEvent):void
		{
			UIManager.getPopUpManager().removePopUp(_recruiteArmsPanel);
			var armProduceMes:Object = {};
			armProduceMes.serverId = e.data.serverId;
			armProduceMes.eid = e.data.eId;
//			_buildingModelData.sendBuildProduction(armProduceMes);
		}
		
		/**
		 *	弹出建筑升级面板 
		 */		
		private function showBuildingUp(buildingObj:BuildingObj):void
		{
//			var buildingObj:BuildingObj = buildingInfoArray[3] as BuildingObj;
			var userInfo:UserInfoObj = appCommonData.userInfo;
			_buildingUpTabView = new BuildingUpTabView(buildingObj);
			_buildingUpTabView.buildingUpTabPanel.userInfo = userInfo;
			_buildingUpTabView.select();
			_buildingUpTabView.checkBuild();
			UIManager.getPopUpManager().addPopUp(_buildingUpTabView);
			
			_buildingUpTabView.addEventListener(BuildEvent.BUILD_UP_CLOSE, closeBuildingUpTabView);
			_buildingUpTabView.addEventListener(BuildEvent.BUILD_UPGRADE, upgradeEvtHandler);
		}
		
		/**
		 * DIY模式 有建筑被添加到场景 
		 * @param e
		 * 
		 */		
		private function isoAddedHandler(e:SceneCommand):void{
			if(!_addIsoDic){
				_addIsoDic = new Dictionary();
			}
			_addIsoDic[e.target] = e.target;
		}
		
		/**
		 * DIY模式 有建筑的移动 
		 * @param e
		 * 
		 */
		private function isoMoveHandler(e:SceneCommand):void{
			if(_addIsoDic && _addIsoDic[e.target])
			{
				_addIsoDic[e.target] = e.target;
				return;
			}
			
			if(!_moveIsoDic){
				_moveIsoDic = new Dictionary();
			}
			var to_x:Number = e.target.absIsoPosition.x;
			var to_y:Number = e.target.absIsoPosition.z;
			var from_x:Number = (e.data.from.x-e.data.to.x)/SceneConst.GRID_SIZE +to_x;
			var from_y:Number = (e.data.from.z-e.data.to.z)/SceneConst.GRID_SIZE +to_y;
			_moveIsoDic[e.target] = {"building":e.target,"from_x":from_x,"from_y":from_y,"to_x":to_x,"to_y":to_y};
		}
		
		/**
		 * DIY模式 被添加的建筑被移除，以及原有建筑被移除
		 * @param e
		 * 
		 */		
		private function isoClearHandler(e:SceneCommand):void {
			if(!_removeIsoDic){
				_removeIsoDic = new Dictionary();
			}
			_removeIsoDic[e.target] = e.target;
			
			if(_addIsoDic){
				delete _addIsoDic[e.target];
			}
			
			if(_moveIsoDic){
				delete _moveIsoDic[e.target];
			}
		}
		
		/**
		 * 弹出环形菜单 
		 * @param e
		 * 
		 */		
		private var eId:String;
		private function isoClickHandler(e:SceneCommand):void {
			if(e.target is BuildingIsoObject) {
				_selectedBuilding = e.target as BuildingIsoObject;
				if(e.actionType == ActionType.NORMAL){
					if(((e.target as BuildingIsoObject).dataObj.status!=BuildConst.STATUS_FOUNDATION
						&&((e.target as BuildingIsoObject).dataObj as BuildingObj).effectAry.length>0)){
						if(_clickIso) {
							UIManager.getToolTipManager().hideTips(_clickIso);
						}
						if(!_buildingRing) {
							_buildingRing = new BaseRingCircle();
						}
						_isShowRing = true;
						_clickIso  = e.target as JusticeIsoObject;
						var $iso:JusticeIsoObject = e.target as JusticeIsoObject;
						eId = e.target.eId;
						UIManager.getToolTipManager().showTips(_buildingRing,$iso,$iso.dataObj,ToolTipManager.UP,ToolTipManager.PASSIVE);
						_buildingRing.addEventListener(BuildEvent.BUILD_RING_ITEM_CLICK,ringItemClickHandler);
						_buildingRing.x = e.data.point.x - _buildingRing.width/2 - 10;
						if((_clickIso.dataObj as BuildingObj).subType==BuildConst.SUBTYPE_GATE){
							_buildingRing.y = e.data.point.y - _buildingRing.height/2 - 50;
						}else{
							_buildingRing.y = e.data.point.y - _buildingRing.height/2;
						}
					}
				}
				
				if(e.actionType == ActionType.REMOVE)
				{
					popUpConfirmPanel(2);
				}
			}
		}
		
		
		/**
		 * 后台返回生产请求结果，在此方法内抛命令给sceneController,
		 * 开始生产倒计时
		 * @param cmd
		 */		
		private function buildProduce(cmd:BuildCommand):void
		{
			trace("开始倒计时");
			var $dataObject:Object = cmd.data;
			if($dataObject.canProduce == 1)
			{
				if($dataObject.hasOwnProperty("gold"))
				{
					appCommonData.userInfo.gold -= $dataObject.gold;
				}
				if($dataObject.hasOwnProperty("iron"))
				{
					appCommonData.userInfo.iron -= $dataObject.iron;
				}
				if($dataObject.hasOwnProperty("wood"))
				{
					appCommonData.userInfo.wood -= $dataObject.wood;
				}
				if($dataObject.hasOwnProperty("stone"))
				{
					appCommonData.userInfo.wood -= $dataObject.stone;
				}
				
				var $cmd:Command = new Command(MainCmdConst.MAIN_CMD_USERINFO);
				$cmd.data = appCommonData.userInfo;
				dispatch($cmd);
				
				var sceneProduceCmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_MODIFY_ISOOBJECT);
				var produceMes:Object = {};
				produceMes.eId = $dataObject.eid;
				produceMes.dataObj = {"currentOrderArr":$dataObject.cur_order_arr, "status":$dataObject.status};
				sceneProduceCmd.data = produceMes;
				dispatch(sceneProduceCmd);
			}
			else
			{
				trace("不能生产");
			}
		}
		
		/**
		 * 后台返回收获结果，在此方法内抛命令给sceneController,
		 * 开始弹出收获动画（比如弹出金币，点击收获）
		 * @param cmd
		 */		
		private function buildHarvest(cmd:BuildCommand):void
		{
			var harvestMes:Object = cmd.data;
			if(harvestMes.can_harvest == 1)
			{
				trace("收获成功啦");
				
				var sceneHarvestCmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_MODIFY_ISOOBJECT);
				
				
				var value:Object = {};
				value.eId = harvestMes.eid;
				value.type = harvestMes.type;
				value.num = harvestMes.output;
				var harvestCmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_DROP_ITEM);
				harvestCmd.data = value;
				dispatch(harvestCmd);
			}
			else
			{
				trace("收获出错啦");
			}
		}
		
		/**
		 * 环形菜单内选项点击处理 
		 * @param e
		 */		
		private function ringItemClickHandler(e:BuildEvent):void{
			var $cmd:Command;
			if(e.data){
				switch(e.data.type){
					case BuildConst.BUILD_REPAIR:
						break;
					case BuildConst.BUILD_UPDATA:
						//						$cmd= new Command(BuildCommand.BUILD_UPDATA,this);
//						showBuildingUp(e.currentTarget.ringObj as BuildingObj);
						showBuildingUp(_selectedBuilding.dataObj as BuildingObj);
						break;
					case BuildConst.BUILD_EDIT:
						$cmd= new Command(EditTroopCmdConst.EDIT_TROOP_INFO_PANEL,this);
						$cmd.data = new Object;
						$cmd.data.eIde= eId;
						break;
					case BuildConst.BUILD_RECRIUT:
						openArmsPanel();
						break;
					case BuildConst.BUILD_ARCHER_EQUIP:
						_archerEquipPanel = new WeaponProducePanel(getEquipObjArr("弓兵",_armsConfigArray));
						UIManager.getPopUpManager().addPopUp(_archerEquipPanel)
						break;
					case BuildConst.BUILD_INFANTRY_EQUIP:
						_infantryEquipPanel = new WeaponProducePanel(getEquipObjArr("步兵",_armsConfigArray));
						UIManager.getPopUpManager().addPopUp(_infantryEquipPanel)
						break;
					case BuildConst.BUILD_CAVALRY_EQUIP:
						_cavalryEquipPanel = new WeaponProducePanel(getEquipObjArr("骑兵",_armsConfigArray));
						UIManager.getPopUpManager().addPopUp(_cavalryEquipPanel)
						break;
					case BuildConst.BUILD_KNIGHT_RECRIUT:
						break;
					case BuildConst.BUILD_KNIGHT_MANAGE:
						break;
					case BuildConst.BUILD_FARM:
						openFarmProducePanel();
						break;
					case BuildConst.BUILD_NAKED_SOLDIERS_HARVEST:
						break;
					case BuildConst.BUILD_ARCHER_IMMEDIATELY_HARVEST_EQUIPMENT:
						break;
					case BuildConst.BUILD_CAVALRY_IMMEDIATELY_HARVEST_EQUIPMENT:
						break;
					case BuildConst.BUILD_INFANTRY_IMMEDIATELY_HARVEST_EQUIPMENT:
						break;
					case BuildConst.BUILD_GATE:
						if(_selectedBuilding.parts)
						{
							var $leftGate:BuildingIsoObject = _selectedBuilding.parts[1];
							var $rightGate:BuildingIsoObject = _selectedBuilding.parts[2];
							_buildingModelData.sendChangeDoorStatus($leftGate.eId,$rightGate.eId,_selectedBuilding.walkable == 0 ? 1 : 0);
						}
						break;
				}
			}
			if($cmd){
				dispatch($cmd);
			}
			hideBuildingRing();
		}
		
		/**
		 *处理model给的arms配置得到兵种装备配置 
		 * @param arr
		 * @return 
		 * 
		 */		
		private function getEquipObjArr(name:String,arr:Array):Array
		{///步兵
			var $equipInfantryArr:Array = new Array();
			///弓箭兵
			var $equipArcherArr:Array = new Array();
			//骑兵
			var $equipCavalryArr:Array = new Array();
			for(var i:uint = 0;i<arr.length;i++)
			{
				if((arr[i] as ArmsConfigObj).equip.type == "步兵")
				{
					$equipInfantryArr.push(arr[i].equip);
				}
				if((arr[i] as ArmsConfigObj).equip.type == "弓兵")
				{
					$equipArcherArr.push(arr[i].equip);
				}
				if((arr[i] as ArmsConfigObj).equip.type == "骑兵")
				{
					$equipCavalryArr.push(arr[i].equip);
				}
			}
			if(name == "步兵")
			{
				return $equipInfantryArr;
			}
			if(name == "弓兵")
			{
				return $equipArcherArr;
			}
			if(name == "骑兵")
			{
				return $equipCavalryArr;
			}
			return null;
		}
		
		/**
		 *	 打开农田生产面板
		 */		
		private function openFarmProducePanel():void
		{
			_farm = new FarmProducePanel();
			_farm.addEventListener(BuildEvent.PRODUCE, farmProduceHandler);
			_farm.changRecruitData(_buildingModelData.orderConfigArr);
			UIManager.getPopUpManager().addPopUp(_farm);
		}
		
		/**
		 * 打开招募面板 
		 * 
		 */		
		private function openArmsPanel():void{
			_recruiteArmsPanel = new RecruiteArmsPanel();
			_recruiteArmsPanel.addEventListener(BuildEvent.PRODUCE, armProduceHandler);
			_recruiteArmsPanel.changRecruitData(_buildingModelData.orderConfigArr);
			UIManager.getPopUpManager().addPopUp(_recruiteArmsPanel,true);
		}
		
		private function sceneDownHandler(e:SceneCommand):void{
			if((e.target&&!e.target is BuildingIsoObject)||e.target==null){
				hideBuildingRing();
			}
		}
		
		private function uiLayerClick(e:MouseEvent):void{
			hideBuildingRing();
		}
		
		/**
		 * 隐藏环形菜单 
		 * 
		 */		
		private function hideBuildingRing(e:Command = null):void{
			if(_clickIso){
				UIManager.getToolTipManager().hideTips(_clickIso);
				_isShowRing = false;
				_clickIso = null;
			}
		}
		
		/**
		 *	建筑升级事件监听器
		 */		
		private function upgradeEvtHandler(e:BuildEvent):void
		{
			switch(e.type){
				
				case BuildEvent.BUILD_UPGRADE:
					if(_buildingUpTabView.buildingUpTabPanel.canUp)
					{
						trace("yes");
						UIManager.getPopUpManager().removePopUp(_buildingUpTabView);
						//				var serverId:String = _buildingUpTabView.
						var data:Object = {"eId":eId}
						_buildingModelData.sendUpgradeStart(data);
					}
					else
					{
						trace("no");
					}break;
				
			}
		}
		
		/**
		 * 建筑升级命令监听器
		 */
		private function upgradeCmdHandler(cmd:BuildCommand):void{
			switch(cmd.cmdName){
				case BuildCommand.BUILD_UPGRADE_START:
					var sceneCmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_MODIFY_ISOOBJECT);
					var data:Object = {};					
					data.eId = cmd.data.eId;
					data.dataObj = {"status":1,"completeTime":App.stime+1,"level":_selectedBuilding.dataObj.level+1};
					sceneCmd.data = data;
					dispatch(sceneCmd);
					break;
				
				case BuildCommand.BUILD_UPGRADE_END:
					break;
				
				
			}
		}
		
		/**
		 *	关闭建筑升级面板 
		 */		
		private function closeBuildingUpTabView(e:BuildEvent):void
		{
			UIManager.getPopUpManager().removePopUp(_buildingUpTabView);
		}
		
		//		/**
		//		 *	���Ҷ�ӦserverId�Ľ���������� 
		//		 * 	@param buildingObj
		//		 */		
		//		public function searchBuildingData(buildingObj:BuildingObj):BuildingObj
		//		{
		//			var tempObj:BuildingObj;
		//			for(var i:int = 0; i < buildingInfoArray.length; i++)
		//			{
		//				if((buildingInfoArray[i] as BuildingObj).serverId == buildingObj.serverId)
		//				{
		//					return (buildingInfoArray[i] as BuildingObj)
		//				}
		//			}
		//			return null;
		//		}
		
		/**
		 * 建筑事件监听 
		 * @param e 建筑事件
		 */
		private function buildEvtHandler(e:BuildEvent):void
		{			
			var cmd:BuildCommand;
			switch(e.type)
			{
				case BuildEvent.BUILD_LIST_ITEM_SELECT:
					if((e.data as BuildListItem).canBuild)
					{
						showListPanel(false);
						cmd = new BuildCommand(BuildCommand.SELECT_BUILDLISTITEM,e.target);
						cmd.data = e.data.data.buildingObj;						
					}else
					{
//						if(!(e.data as BuildListItem).resourceEnoughArray[0])
//						resourceTips = new BuildingResourceTips("");
//						UIManager.getPopUpManager().addPopUp(resourceTips,false,true,true,true);
//						resourceTips.y -= 200;
						
						(e.data as BuildListItem).showResourceTips();
						trace("资源不够！");
					}
					break;
				
				case BuildEvent.BUILD_BUTTON_SELECT:
					switch(e.data)
					{
						case "build":
							cmd = new BuildCommand(BuildCommand.DIY_BUILD);
							popUpBuildListPanel();
							showListPanel(true);
							break;
						
						case "confirm":
							cmd = new BuildCommand(BuildCommand.DIY_CONFIRM);
							closeConfirmPanel();
							closeBuildingButtonsPanel();
							buildingConstructionConfirm();
							sendDiyHistory();
							break;
						
						case "cancel":
							cmd = new BuildCommand(BuildCommand.REMOVE_CURRENT_DRAGGING_BUILDING);
							if(_diyHistoryArray && _diyHistoryArray.length > 0)
							{
								popUpConfirmPanel(1);								
							}else{
								closeBuildingButtonsPanel();
								var $cancelCmd:BuildCommand = new BuildCommand(BuildCommand.DIY_CANCEL);
								dispatch($cancelCmd);
							}
							break;
						
						case "move":
							cmd = new BuildCommand(BuildCommand.DIY_MOVE);
							break;
						
						case "remove":
							cmd = new BuildCommand(BuildCommand.DIY_REMOVE);
							break;
						
						case "regain":
							cmd = new BuildCommand(BuildCommand.DIY_MOVETOBAG);
							break;
						
						default:
							break;
					}break;//break掉内层的switch
				
				case BuildEvent.BUILD_CLOSE:
					//					cmd = new BuildCommand(BuildCommand.CLICK_BUILD_CANCEL_BUTTON);
					showListPanel(false);
					//					closeBuildingButtonsPanel();
					//					popUpConfirmPanel(0);
					break;
				
				case BuildEvent.CONFIRMPANEL_SAVE:
					//					cmd = new BuildCommand(BuildCommand.BUILD_CONFIRM);
					closeConfirmPanel();
					sendDiyHistory();
					//					closeBuildingButtonsPanel();
					break;
				
				case BuildEvent.CONFIRMPANEL_UNDO:
					cmd = new BuildCommand(BuildCommand.DIY_REVERT);
					cmd.data = _diyHistoryArray;
					closeConfirmPanel();
					closeBuildingButtonsPanel();
					
					var cancelCmd:BuildCommand = new BuildCommand(BuildCommand.DIY_CANCEL);
					dispatch(cancelCmd);
					
					var $cmd:Command = new Command(MainCmdConst.MAIN_CMD_USERINFO);
					$cmd.data = _originUserInfo;
					dispatch($cmd);
					break;
				
				case BuildEvent.CONFIRMPANEL_REMOVE:
					closeConfirmPanel();
					cmd = new BuildCommand(BuildCommand.DIY_REMOVE_CONFIRM);
					cmd.data = _selectedBuilding;
					break;
				
				case BuildEvent.CONFIRMPANEL_REMAIN:
					closeConfirmPanel();
					break;
				
				default:
					break;
			}
			
			if(cmd){
				trace(cmd.cmdName);
				dispatch(cmd);
			}
		}
		
		
		/**
		 * 摆放、移除、移动建筑成功信息返回 
		 * @param e
		 * 
		 */		
		private function buildConstructionHandler(e:BuildCommand):void 
		{
			switch(e.cmdName)
			{
				case BuildCommand.BUILD_CONSTRUCTION_SUCCESS:
					if(e.data)
					{
						for each(var obj:Object in e.data)
						{
							for each(var buildIso:BuildingIsoObject in _addIsoDic)
							{
								if(obj.x == buildIso.absIsoPosition.x&&obj.y ==buildIso.absIsoPosition.z)
								{
									var buildObj:BuildingObj = (buildIso.dataObj as BuildingObj).clone();
									buildObj.completeTime = obj.completed_time;
									buildObj.status = obj.status;
									buildObj.level = obj.level;
									buildIso.dataObj= buildObj;
									buildIso.isoDataObj.eId = String(obj.eid);
									(buildIso as BuildingIsoObject).checkIsConstruction();
									delete _addIsoDic[buildIso];
									break;
								}
							}
						}
						_addIsoDic = null;
					}break;
				
				case BuildCommand.REMOVE_CONSTRUCTION_SUCCESS:
					if(e.data){
						_removeIsoDic = null;
					}break;
				
				case BuildCommand.MOVE_CONSTRUCTION_SUCCESS:
					if(e.data){
						_moveIsoDic = null;
					}break;
				default:
					break;				
			}
		}
		
		private function buildingConstructionConfirm():void{
			if(_removeIsoDic){
				var removeArray:Array = [];
				for each(var removeObj:JusticeIsoObject in _removeIsoDic){
					if(removeObj is BuildingIsoObject){
						var removeBuildInfo:Object = {};
						removeBuildInfo.x = (removeObj as BuildingIsoObject).absIsoPosition.x;
						removeBuildInfo.y = (removeObj as BuildingIsoObject).absIsoPosition.z;
						removeBuildInfo.eid = (removeObj as BuildingIsoObject).eId;
						removeArray.push(removeBuildInfo);
					}
				}
				_buildingModelData.sendRemoveConstruction(removeArray);
			}
			if(_moveIsoDic){
				var moveArray:Array = [];
				for each(var object:Object in _moveIsoDic){
					if(object.building is BuildingIsoObject){
						var moveInfo:Object = {};
						moveInfo.from_x = object.from_x;
						moveInfo.from_y = object.from_y;
						moveInfo.to_x = object.to_x;
						moveInfo.to_y = object.to_y;
						moveInfo.eid = (object.building as BuildingIsoObject).eId;
						moveArray.push(moveInfo);
					}
				}
				_buildingModelData.sendMoveConstruction(moveArray);
			}
			if(_addIsoDic){
				var ary:Array = []
				for each(var obj:JusticeIsoObject in _addIsoDic){
					if(obj is BuildingIsoObject){
						var buildInfo:Object = {};
						buildInfo.x = (obj as BuildingIsoObject).absIsoPosition.x;
						buildInfo.y = (obj as BuildingIsoObject).absIsoPosition.z;
						buildInfo.type = ((obj as BuildingIsoObject).dataObj as BuildingObj).serverId;
						ary.push(buildInfo);
					}
				}
				_buildingModelData.sendBuildConstruction(ary);
			}
		}
		
		
		/**
		 * DIY模式点击确定时，建筑列表里的建筑开始变成地基 
		 * 
		 */		
		private function showBuildConstruction():void{
			if(_addIsoDic){
				for each(var obj:JusticeIsoObject in _addIsoDic){
					if(obj is BuildingIsoObject){
						(obj as BuildingIsoObject) .checkIsConstruction();
					}
					delete _addIsoDic[obj];
				}
			}
			_addIsoDic = null;
		}
		
		/**
		 * 建筑命令监听 
		 * @param cmd 建筑命令
		 */
		private function buildCmdHandler(cmd:BuildCommand):void
		{
			switch (cmd.cmdName)
			{
				case BuildCommand.CLICK_BUILD_OPEN_BUTTON:
					popUpBuildListPanel();
					if(appCommonData.userInfo)
					{
						_originUserInfo = appCommonData.userInfo.clone();						
					}else 
					{
						trace("空的用户信息！");
						_originUserInfo = new UserInfoObj();
					}
					_diyHistoryArray = [];
					
					var $cmd:BuildCommand = new BuildCommand(BuildCommand.DIY_MOVE);
					dispatch($cmd);
					break;
				
				case BuildCommand.CONSTRUCTION_COMPLETE:
					//					showListPanel(true);
					//这个命令废弃不用
					break;
				
				default:
					break;
			}
		}
		
		/**
		 * 场景命令监听 
		 * @param cmd
		 */
		private function sceneCmdHandler(cmd:SceneCommand):void
		{
			switch(cmd.cmdName)
			{
				case SceneCommand.SCENE_CMD_CLICK_ISO:
					if(cmd.target)
					{
						
					}
					break;
				
				case SceneCommand.SCENE_CMD_MOUSE_MOVE:
					if(cmd.target is BuildingIsoObject 
						&& cmd.actionType == ActionType.NORMAL&&!_isShowRing
						&&(cmd.target as BuildingIsoObject).dataObj.subType!=BuildConst.SUBTYPE_RODE
						&&(cmd.target as BuildingIsoObject).dataObj.subType!=BuildConst.SUBTYPE_GATE
						&&(cmd.target as BuildingIsoObject).dataObj.subType!=BuildConst.SUBTYPE_WALL)
					{
						
						showBuildingTips(cmd.target as BuildingIsoObject,cmd.data.point);
					}
					break;
				
				case SceneCommand.SCENE_ACTION_ADD:
					//	暂用
					
					var $cmd:Command = new Command(MainCmdConst.MAIN_CMD_USERINFO);
					$cmd.data = appCommonData.userInfo;
					dispatch($cmd);
					isoAddedHandler(cmd);
					
					if(appCommonData.userInfo)
					{
						appCommonData.userInfo.gold -= cmd.data.commodityObj.gold;
						appCommonData.userInfo.iron -= cmd.data.commodityObj.iron;
						appCommonData.userInfo.wood -= cmd.data.commodityObj.wood;
						appCommonData.userInfo.stone -= cmd.data.commodityObj.stone;
						appCommonData.userInfo.prosperity += cmd.data.levelInfo[0].prosperity;
						$cmd = new Command(MainCmdConst.MAIN_CMD_USERINFO);
						$cmd.data = appCommonData.userInfo;
						dispatch($cmd);						
					}
					_diyHistoryArray.push(cmd);//记录添加动作
					break;
				case SceneCommand.SCENE_ACTION_MOVE:
					isoMoveHandler(cmd);
					_diyHistoryArray.push(cmd);
					break;
				case SceneCommand.SCENE_ACTION_REMOVE:
					isoClearHandler(cmd);
					_diyHistoryArray.push(cmd);					
					break;
				case SceneCommand.SCENE_CMD_ISO_DISPATCH_EVENT:
					exeIsoEvent(cmd.data.event,cmd.data.isoDataObj,cmd.data.dataObj);
					break;
			}
		}
		
		private function exeIsoEvent(event:Event,isoDataObj:IsoDataObj,dataObj:Object):void
		{
			switch(event.type)
			{
				case BuildEvent.PRODUCE:
					trace("生产");
					_buildingModelData.sendBuildProduction((event as BuildEvent).data);
					break;
				case BuildEvent.HARVEST_CLICK:
					var object:Object = {};
					object.eid = isoDataObj.eId;
					_buildingModelData.sendBuildHarvest(object);
					break;
				default:
					break;
			}
		}
		
		private function showListPanel(value:Boolean):void
		{
			_buildingListPanel.visible = value;
			_buildingButtonsPanel.visible = !value;
		}
		
		/**
		 * 显示建筑提示 
		 * @param obj 要显示提示的建筑
		 * @param type 1：建筑物处于闲置状态，2：建筑处于生产状态
		 * @param point 建筑所在屏幕坐标
		 */
		private function showBuildingTips(obj:BuildingIsoObject, point:Point, type:int = 1):void
		{
			var $cmd:BuildCommand = new BuildCommand(BuildCommand.RESOUSE_GOLD);
			var $obj:Object = new Object;
			$obj.x = point.x;
			$obj.y = point.y;
			$obj.type = "gold";
			$obj.num = "10";
			$cmd.data = $obj;
			dispatch($cmd);
			var buildingStatus:int  =((obj.dataObj) as BuildingObj).status;
			var buildingObj:BuildingObj = obj.dataObj as BuildingObj;
			var tipData:Object = {};
			//	建造状态
			if(buildingStatus == 1)
			{
				obj.showProgress();
			}
			//	闲置状态
			else if(buildingStatus == 2)	
			{
				tipData.data = buildingObj;
				tipData.type = 1;
				UIManager.getToolTipManager().showTips(BuildingTips, obj, tipData, ToolTipManager.UP, ToolTipManager.ITEM_OUT);
			}
			//	处于生产状态
			else if(buildingStatus == 3)
			{
				if(buildingObj.subType != BuildConst.SUBTYPE_SORLIDER)
				{
					tipData.data = buildingObj;
					tipData.type = 2;
					UIManager.getToolTipManager().showTips(BuildingTips, obj, tipData, ToolTipManager.UP, ToolTipManager.ITEM_OUT);
				}
			}
			//	可收获状态
			else if(buildingStatus == 4){}
			//	损坏状态
			else if(buildingStatus == 5){}
			//	废墟状态
			else{}
		}
		
		/**
		 * 弹出建筑列表面板 
		 */
		private function popUpBuildListPanel():void
		{
			if(!_buildingListPanel)
			{
				_buildingListPanel = new BuildingListPanel(buildingListData);
				_buildingListPanel.addEventListener(BuildEvent.BUILD_LIST_ITEM_SELECT, buildEvtHandler);
				_buildingListPanel.addEventListener(BuildEvent.BUILD_CLOSE, buildEvtHandler);
				//				_buildingListPanel.data = buildingInfoArray;
			}
			_buildingListPanel.visible = false;
			UIManager.getPopUpManager().addPopUp(_buildingListPanel,false);
			
			if(!_buildingButtonsPanel)
			{
				_buildingButtonsPanel = new BuildingButtonsPanel();
				_buildingButtonsPanel.addEventListener(BuildEvent.BUILD_BUTTON_SELECT, buildEvtHandler);
			}
			_buildingButtonsPanel.visible = true;
			
			UIManager.getPanelManager().addPanel(_buildingButtonsPanel);
			App.appStage.addEventListener(Event.RESIZE, onResize);
			updateView();
		}
		
		private function sendDiyHistory():void
		{
			//TODO 发送前命令需要合并
		}
		
		/**
		 * 构造建筑列表面板所需数据 
		 */
		private function get buildingListData():Array
		{
			var array:Array = [];
			var userInfo:UserInfoObj = appCommonData.userInfo;
			for(var i:int=0;i<buildingInfoArray.length;i++)
			{
				array.push({"buildingObj":buildingInfoArray[i],"userInfo":userInfo});
			}
			
			return array;
		}
		
		/**
		 * 弹出确认框 
		 */
		private function popUpConfirmPanel(type:int):void
		{
			//			if(!_buildingConfirmPanel)
			{
				_buildingConfirmPanel = new BuildingConfirmPanel(type);
				_buildingConfirmPanel.addEventListener(BuildEvent.CONFIRMPANEL_SAVE, buildEvtHandler);
				_buildingConfirmPanel.addEventListener(BuildEvent.CONFIRMPANEL_UNDO, buildEvtHandler);
				_buildingConfirmPanel.addEventListener(BuildEvent.CONFIRMPANEL_REMOVE, buildEvtHandler);
				_buildingConfirmPanel.addEventListener(BuildEvent.CONFIRMPANEL_REMAIN, buildEvtHandler);
			}
			UIManager.getPopUpManager().addPopUp(_buildingConfirmPanel,true,true,true,false);
			//			UIManager.getPopUpManager().addPopUp(_buildingConfirmPanel);
			if(_buildingButtonsPanel){
				_buildingButtonsPanel.visible = false;
			}
		}
		
		private function onResize(e:Event):void
		{
			updateView();
		}
		
		/**
		 * 重新显示组件位置 
		 */
		private function updateView():void
		{
			if(_buildingButtonsPanel)
			{
				_buildingButtonsPanel.x = App.appStage.stageWidth - 320;
				_buildingButtonsPanel.y = App.appStage.stageHeight - 150;
				_buildingButtonsPanel.x = App.appStage.stageWidth - _buildingButtonsPanel.width;
				_buildingButtonsPanel.y = App.appStage.stageHeight - _buildingButtonsPanel.height;
				//				_buildingButtonsPanel.x = App.appStage.stageWidth*0.35;
				//				_buildingButtonsPanel.y = App.appStage.stageHeight*0.82;
			}
		}
		
		/**
		 * 关闭建筑列表面板 
		 */
		private function closeBuildingListPanel():void
		{
			if(_buildingListPanel && _buildingListPanel.parent)
			{
				UIManager.getPopUpManager().removePopUp(_buildingListPanel);
				
			}			
		}
		
		/**
		 * 关闭建筑按钮面板 
		 */
		private function closeBuildingButtonsPanel():void
		{
			closeBuildingListPanel();
			if(_buildingButtonsPanel && _buildingButtonsPanel.parent)
			{
				UIManager.getPopUpManager().removePopUp(_buildingButtonsPanel);
				
			}
		}
		
		/**
		 * 关闭确认面板 
		 */
		private function closeConfirmPanel():void
		{
			if(_buildingConfirmPanel && _buildingConfirmPanel.parent)
			{
				UIManager.getPopUpManager().removePopUp(_buildingConfirmPanel);
				//				_buildingConfirmPanel = null;
			}
			
			if(_buildingButtonsPanel){
				_buildingButtonsPanel.visible = true;
			}
		}
		
		private function test():void{
			_buildingModelData.buildingInfo;
		}
	}
}